package smartcarpool.smartspaceservice;

/**
 * Created with IntelliJ IDEA.
 * User: tnn
 * Date: 16.08.13
 * Time: 12:25
 * Testing class to check some possibilities of smart space
 */

import android.util.Log;
import sofia_kp.KPICore;

public class SS_KP extends Thread {

    private KPICore kpi_core;
    private String HOST;
    private String joinResult;
    private int PORT;
    private String SPACE_NAME;
    private volatile boolean connectionActive;
    private volatile static SS_KP uniqueKP;

    private SS_KP(String HOST, int PORT, String SPACE_NAME) {
        this.HOST = HOST;
        this.PORT = PORT;
        this.SPACE_NAME = SPACE_NAME;
        kpi_core = new KPICore(HOST,PORT,SPACE_NAME);
        connectionActive = false;
    }

    public static SS_KP getKP(String HOST, int PORT, String SPACE_NAME){
        if (uniqueKP == null){
            synchronized (SS_KP.class){
                if (uniqueKP == null){
                    uniqueKP = new SS_KP(HOST, PORT,SPACE_NAME);
                }
            }

        }
        return uniqueKP;
    }

    @Override
    public void run(){
        super.run();
        Log.d("SmartSpaceKP ", "Start connection to the KP, thread " + String.valueOf(this.getId()));

        joinResult = kpi_core.join();

        if (joinResult != null) {
            if (kpi_core.xmlTools.isJoinConfirmed(joinResult)) {
                Log.d("SmartSpaceKP ", " correct join");
                connectionActive = true;
            } else {
                connectionActive = false;
                Log.d("SmartSpaceKP ", " Problem with join to the "+ HOST + ":"+PORT +" Space Name: "+ SPACE_NAME + ". Check your connection information");
            }
        } else {
            connectionActive = false;
            Log.d("SmartSpaceKP ", " Problem with join to the "+ HOST + ":"+PORT +" Space Name: "+ SPACE_NAME + ". Check your connection information");
        }

        //kpi_core.leave();



    }

    public KPICore getKPICore(){
        return kpi_core;
    }

    public boolean isConnectionActive(){
        return connectionActive;
    }

    public void stopConnection(){
        kpi_core.leave();
        uniqueKP = null;

    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        Log.d("SmartSpaceKP ", " Finalize thread " + String.valueOf(this.getId()));
    }

}
